package com.cloud.netty.ProtocolTcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import java.util.UUID;

/**
 * @program: netty
 * @description:
 * @author: Cloud
 * @create: 2022/4/14 14:25:10
 */
public class ProServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        // 接收数据,并处理
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端信息如下:");
        System.out.println("长度: " + len);
        System.out.println("内容: " + new String(content, CharsetUtil.UTF_8));

        String response = UUID.randomUUID().toString();
        int length = response.getBytes("utf-8").length;
        // 构建一个协议包
        ctx.writeAndFlush(new MessageProtocol(length,response.getBytes(CharsetUtil.UTF_8)));
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
